﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Xml;

using Notepad_X;
namespace Toolbar_Editor_Plugin
{
    public partial class Editor : Form
    {
        String FileName = null;
        String TempFilename;
        String BaseText = "Toolbar editor";
        Notepad_X.Main main = Notepad_X.Static.MainInstance;

        public Editor()
        {
            InitializeComponent();
        }

        private void Editor_Load(object sender, EventArgs e)
        {
            foreach (String name in Enum.GetNames(typeof(Notepad_X.Classes.Strings)))
            {
                if (name != "none")
                {
                    edit_text.Items.Add("system|" + name);
                }
            }
            foreach (String name in Enum.GetNames(typeof(Notepad_X.Classes.Icons)))
            {
                if (name != "none")
                {
                    edit_image.Items.Add("system|" + name);
                }
            }
            TempFilename = Notepad_X.Main.System_ROOT + "\\Toolbars\\ToolbarEditor_temp.xml";
            if (main.IconsCollection.Images.ContainsKey("toolbar"))
            {
                this.Icon = System.Drawing.Icon.FromHandle(new System.Drawing.Bitmap(main.IconsCollection.Images["toolbar"]).GetHicon());
            }
            else
            {
                this.ShowIcon = false;
            }
        }


        private void add_button_Click(object sender, EventArgs e)
        {
            if (ItemsList.SelectedNode!=null && ItemsList.SelectedNode.GetType() == typeof(ToolbarItems) && ((ToolbarItems)ItemsList.SelectedNode).ItemType == ItemsTypes.dropdown)
            {
                ItemsList.SelectedNode.Expand();
                ItemsList.SelectedNode.Nodes.Add(new ToolbarItems(ItemsTypes.button));
            }else{
                ItemsList.Nodes.Add(new ToolbarItems(ItemsTypes.button));
            }
        }

        private void add_dropdown_Click(object sender, EventArgs e)
        {
            ItemsList.Nodes.Add(new ToolbarItems(ItemsTypes.dropdown));
        }

        private void add_seperator_Click(object sender, EventArgs e)
        {
            if (ItemsList.SelectedNode != null && ItemsList.SelectedNode.GetType() == typeof(ToolbarItems) && ((ToolbarItems)ItemsList.SelectedNode).ItemType == ItemsTypes.dropdown)
            {
                ItemsList.SelectedNode.Nodes.Add(new ToolbarItems(ItemsTypes.spectator));
                ItemsList.SelectedNode.Expand();
            }else{
                ItemsList.Nodes.Add(new ToolbarItems(ItemsTypes.spectator));
            }
        }

        private void add_label_Click(object sender, EventArgs e)
        {
            if (ItemsList.SelectedNode != null && ItemsList.SelectedNode.GetType() == typeof(ToolbarItems) && ((ToolbarItems)ItemsList.SelectedNode).ItemType == ItemsTypes.dropdown)
            {
                ItemsList.SelectedNode.Expand();
                ItemsList.SelectedNode.Nodes.Add(new ToolbarItems(ItemsTypes.label));
            }else{
                ItemsList.Nodes.Add(new ToolbarItems(ItemsTypes.label));
            }
        }

        private void ItemsList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (ItemsList.Nodes.Count > 0 && ItemsList.SelectedNode.GetType() == typeof(ToolbarItems))
            {
                edit_text.Text = ItemsList.SelectedNode.Text;
                edit.Enabled = true;
                edit_code.Enabled = false;
                remove.Enabled = true;
                edit_code.Text = null;

                edit_style.Text = Enum.GetName(typeof(ItemsStyles), ((ToolbarItems)ItemsList.SelectedNode).ItemStyle);

                edit_image.Text = ((ToolbarItems)ItemsList.SelectedNode).ItemImage;
                switch (((ToolbarItems)ItemsList.SelectedNode).ItemType)
                {
                    //case ItemsTypes.dropdown:
                    //    break;
                    //case ItemsTypes.label:
                    //    break;
                    case ItemsTypes.spectator:
                        edit.Enabled = false;

                        edit_image.Text = null;
                        break;
                    case ItemsTypes.button:
                        edit_code.Enabled = true;
                        edit_code.Text = ((ToolbarItems)ItemsList.SelectedNode).ItemCode;
                        break;
                }
                edit_style_SelectionChangeCommitted(null, null);
            }else{
                remove.Enabled = false;
                edit.Enabled = false;
                edit_code.Enabled = false;
            }
            up.Enabled= !(ItemsList.SelectedNode.Index == 0);
            down.Enabled = !(ItemsList.SelectedNode.Index == ItemsList.Nodes.Count-1);
        }

        private void remove_Click(object sender, EventArgs e)
        {
            if (ItemsList.SelectedNode != null) 
                ItemsList.SelectedNode.Remove();
        }

        private void up_Click(object sender, EventArgs e)
        {
            int index = ItemsList.SelectedNode.Index;
            ToolbarItems tempitem = (ToolbarItems)ItemsList.Nodes[index];
            ToolbarItems tempitem2 = (ToolbarItems)ItemsList.Nodes[index -1];

            ItemsList.Nodes.RemoveAt(index);
            ItemsList.Nodes.RemoveAt(index -1);

            ItemsList.Nodes.Insert(index, tempitem2);
            ItemsList.Nodes.Insert(index -1, tempitem);
            ItemsList.SelectedNode = tempitem;
        }

        private void down_Click(object sender, EventArgs e)
        {

            int index = ItemsList.SelectedNode.Index;
            ToolbarItems tempitem = (ToolbarItems)ItemsList.Nodes[index];
            ToolbarItems tempitem2 = (ToolbarItems)ItemsList.Nodes[index+1];

            ItemsList.Nodes.RemoveAt(index + 1);
            ItemsList.Nodes.RemoveAt(index);
            

            ItemsList.Nodes.Insert(index, tempitem2);
            ItemsList.Nodes.Insert(index + 1, tempitem);
            ItemsList.SelectedNode = tempitem;
        }


        private void edit_style_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (edit_style.Text == "text")
            {
                edit_image.Enabled = false;
                edit_imagePreview.Image = null;
            }
            else
            {
                edit_image.Enabled = true;
            }
        }

        private void edit_image_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (edit_image.Text.Contains("|"))
            {
                string[] spl = edit_image.Text.Split('|');
                if (spl[0] == "system")
                {
                    if (main.IconsCollection.Images.ContainsKey(spl[1]))
                    {
                        try
                        {
                            edit_imagePreview.Image = main.IconsCollection.Images[spl[1]];
                        }catch(Exception){}
                    }
                    else
                    {
                        edit_imagePreview = null;
                    }

                }
            }else{
                if (FileName != null)
                {
                    String path = new System.IO.FileInfo(FileName).Directory.ToString();

                    if (path.EndsWith("\\") != true)
                    {
                        path += "\\";
                    }

                    if (edit_image.Text.ToLower().Contains("{folder}") == true)
                    {
                        if (System.IO.File.Exists(path + info_Imagefolder + "\\" + edit_image.Text.Replace("{folder}", "")))
                        {
                            edit_imagePreview.Image = System.Drawing.Image.FromFile(path + info_Imagefolder + "\\" + edit_image.Text.Replace("{folder}", ""));
                        }
                    }
                    else
                    {
                        if(System.IO.File.Exists(path + edit_image.Text))
                        {
                            edit_imagePreview.Image = System.Drawing.Image.FromFile(path + edit_image.Text);
                        }
                    }
                }
            }
        }

        private void apply_Click(object sender, EventArgs e)
        {
            ItemsList.SelectedNode.Text = edit_text.Text;

            ((ToolbarItems)ItemsList.SelectedNode).ItemStyle = (ItemsStyles)Enum.Parse(typeof(ItemsStyles), edit_style.Text,true);
            if (((ToolbarItems)ItemsList.SelectedNode).ItemStyle == ItemsStyles.text)
            {
                ((ToolbarItems)ItemsList.SelectedNode).ItemImage = null;
            }
            else
            {
                ((ToolbarItems)ItemsList.SelectedNode).ItemImage = edit_image.Text;
            }

            if (((ToolbarItems)ItemsList.SelectedNode).ItemType ==  ItemsTypes.button)
            {
               
                    ((ToolbarItems)ItemsList.SelectedNode).ItemCode = edit_code.Text;
            }
            ItemsList.Focus();
         
        }

        private void edit_image_SelectedIndexChanged(object sender, EventArgs e)
        {
            edit_image_SelectionChangeCommitted(null, null);
        }

        private void edit_image_TextUpdate(object sender, EventArgs e)
        {
            edit_image_SelectionChangeCommitted(null, null);
        }

        private void menu_new_Click(object sender, EventArgs e)
        {
            this.Text = BaseText;
            FileName = null;
            info_Name.Text = info_Author.Text = info_Description.Text = info_Version.Text = info_Imagefolder.Text = null;
            ItemsList.Nodes.Clear();
            previewToolbar.Items.Clear();
        }

        private void menu_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenToolbar = new OpenFileDialog();
            OpenToolbar.Filter = "Notepad X Toolbar Files (*.xml)|*.xml";
            OpenToolbar.InitialDirectory = Notepad_X.Main.System_ROOT + "\\Toolbars\\";
            OpenToolbar.Multiselect = false;
            if (OpenToolbar.ShowDialog() == DialogResult.OK)
            {
                String[] Hash = Notepad_X.Classes.Toolbar.hashToolbar(OpenToolbar.FileName);
                if (Hash == null)
                {
                    MessageBox.Show("Error invalid toolbar file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    ItemsList.Nodes.Clear();
                    FileName = OpenToolbar.FileName;
                    this.Text = BaseText + " - " + FileName;

                    info_Name.Text = Hash[0];
                    info_Author.Text = Hash[1];
                    info_Version.Text = Hash[2];
                    info_Description.Text = Hash[3];

                    XmlDocument xmlFile = new XmlDocument();
                    xmlFile.Load(FileName);


                    if (xmlFile.SelectNodes("Toolbar/Information/ImageFolder").Count != 0)
                    {
                        info_Imagefolder.Text = xmlFile.SelectSingleNode("Toolbar/Information/ImageFolder").InnerText;
                    }else{
                        info_Imagefolder.Text = null;
                    }


                    XmlNodeList nodes = xmlFile.SelectNodes("Toolbar/Item");

                    if (nodes.Count != 0)
                    {
                        foreach (XmlNode node in nodes)
                        {
                            
                            ToolbarItems nToolbarItem;
                            switch (node.SelectSingleNode("Type").InnerText.ToLower())
                            {
                                case "button":
                                    nToolbarItem = new ToolbarItems(ItemsTypes.button);
                                    if (node.SelectNodes("Code").Count != 0)
                                    {
                                        nToolbarItem.ItemCode = node.SelectSingleNode("Code").InnerText;
                                    }
                                    break;
                                case "label":
                                    nToolbarItem = new ToolbarItems(ItemsTypes.label);
                                    break;
                                case "dropdown":
                                    nToolbarItem = new ToolbarItems(ItemsTypes.dropdown);
                                    break;
                                default:
                                    nToolbarItem = new ToolbarItems(ItemsTypes.spectator);
                                    break;
                            
                            }
                            nToolbarItem.Text = "";
                            ItemsList.Nodes.Add(nToolbarItem);
                            if(nToolbarItem.ItemType!= ItemsTypes.spectator){
                                switch (node.SelectSingleNode("Style").InnerText.ToLower())
                                {
                                    case "image":
                                        nToolbarItem.ItemStyle = ItemsStyles.image;
                                        nToolbarItem.ItemImage = node.SelectSingleNode("Image").InnerText;
                                        if (node.SelectNodes("Text").Count > 0)
                                        {
                                            nToolbarItem.Text = node.SelectSingleNode("Text").InnerText;
                                        }
                                        break;
                                    case "imageandtext":
                                        nToolbarItem.ItemStyle = ItemsStyles.imageandtext;
                                        nToolbarItem.ItemImage = node.SelectSingleNode("Image").InnerText;
                                        nToolbarItem.Text = node.SelectSingleNode("Text").InnerText;
                                        break;
                                    default:
                                        nToolbarItem.ItemStyle = ItemsStyles.text;
                                        nToolbarItem.Text = node.SelectSingleNode("Text").InnerText;
                                        break;
                                }
                                
                                if(nToolbarItem.ItemType == ItemsTypes.dropdown){
                                    foreach (XmlNode subnode in node.SelectNodes("Subitem"))
                                    {
                                        ToolbarItems nSubItem;
                                        switch (subnode.SelectSingleNode("Type").InnerText.ToLower())
                                        {
                                            case "button":
                                                nSubItem = new ToolbarItems(ItemsTypes.button);
                                                if (subnode.SelectNodes("Code").Count != 0)
                                                {
                                                    nSubItem.ItemCode = subnode.SelectSingleNode("Code").InnerText;
                                                }
                                                break;
                                            case "label":
                                                nSubItem = new ToolbarItems(ItemsTypes.label);
                                                break;
                                            default :
                                                nSubItem = new ToolbarItems(ItemsTypes.spectator);
                                                break;
                                        }
                                        nToolbarItem.Nodes.Add(nSubItem);
                                        if (nSubItem.ItemType != ItemsTypes.spectator)
                                        {
                                            switch (subnode.SelectSingleNode("Style").InnerText.ToLower())
                                            {
                                                case "image":
                                                    nSubItem.ItemStyle = ItemsStyles.image;
                                                    nSubItem.ItemImage = subnode.SelectSingleNode("Image").InnerText;
                                                    if (subnode.SelectNodes("Text").Count > 0)
                                                    {
                                                        nSubItem.Text = subnode.SelectSingleNode("Text").InnerText;
                                                    }
                                                    break;
                                                case "imageandtext":
                                                    nSubItem.ItemStyle = ItemsStyles.imageandtext;
                                                    nSubItem.ItemImage = subnode.SelectSingleNode("Image").InnerText;
                                                    nSubItem.Text = subnode.SelectSingleNode("Text").InnerText;
                                                    break;
                                                default:
                                                    nSubItem.ItemStyle = ItemsStyles.text;
                                                    nSubItem.Text = subnode.SelectSingleNode("Text").InnerText;
                                                    break;
                                            }
                                        }

                                    }
                                }
                            }

                            }
                    }//end if (nodes.Count != 0)
                    }
                }
            }
        private void menu_save_Click(object sender, EventArgs e)
        {
            if (FileName == null)
            {
                menu_saveas_Click(null, null);
            }else{
                SaveToolbar(FileName);
            }
        }
        private void menu_saveas_Click(object sender, EventArgs e)
        {
            SaveFileDialog Dialog = new SaveFileDialog();
            Dialog.FileName = info_Name.Text;
            Dialog.Filter = "Notepad X Toolbar Files (*.xml)|*.xml";
            Dialog.InitialDirectory = Notepad_X.Main.System_ROOT + "\\Toolbars\\";
            if (Dialog.ShowDialog() == DialogResult.OK)
            {
                SaveToolbar(Dialog.FileName);
                FileName = Dialog.FileName;
                this.Text = BaseText + " - " + FileName;
            }
        }
        private void SaveToolbar(String Path)
        {
            XmlTextWriter xmlFile = new XmlTextWriter(Path, System.Text.Encoding.UTF8);

            xmlFile.Formatting = Formatting.Indented;

            xmlFile.WriteStartElement("Toolbar");

            xmlFile.WriteStartElement("Information");

            xmlFile.WriteStartElement("Name");
            xmlFile.WriteString(info_Name.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Author");
            xmlFile.WriteString(info_Author.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Version");
            xmlFile.WriteString(info_Version.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Description");
            xmlFile.WriteString(info_Description.Text);
            xmlFile.WriteEndElement();


            xmlFile.WriteStartElement("ImageFolder");
            xmlFile.WriteString(info_Name.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteEndElement(); // Close Informations

            foreach (ToolbarItems item in ItemsList.Nodes)
            {
                xmlFile.WriteStartElement("Item");

                xmlFile.WriteStartElement("Type");
                xmlFile.WriteString(Enum.GetName(typeof(ItemsTypes),item.ItemType));
                xmlFile.WriteEndElement();
                if (item.ItemType != ItemsTypes.spectator)
                {
                    if (item.ItemType == ItemsTypes.button)
                    {
                        xmlFile.WriteStartElement("Code");
                        xmlFile.WriteString(item.ItemCode);
                        xmlFile.WriteEndElement();
                    }
                    xmlFile.WriteStartElement("Style");
                    xmlFile.WriteString(Enum.GetName(typeof(ItemsStyles), item.ItemStyle));
                    xmlFile.WriteEndElement();

                    if (item.ItemStyle != ItemsStyles.image)
                    {
                        xmlFile.WriteStartElement("Text");
                        xmlFile.WriteString(item.Text);
                        xmlFile.WriteEndElement();
                    }

                    //if (item.ItemStyle != ItemsStyles.text)
                    //{
                        xmlFile.WriteStartElement("Image");
                        xmlFile.WriteString(item.ItemImage);
                        xmlFile.WriteEndElement();
                    //}
                    if (item.ItemType == ItemsTypes.dropdown)
                    {
                        foreach (ToolbarItems subitem in item.Nodes)
                        {
                            xmlFile.WriteStartElement("Subitem");

                            xmlFile.WriteStartElement("Type");
                            xmlFile.WriteString(Enum.GetName(typeof(ItemsTypes), subitem.ItemType));
                            xmlFile.WriteEndElement();

                            if (subitem.ItemType != ItemsTypes.spectator)
                            {
                                if (subitem.ItemType == ItemsTypes.button)
                                {
                                    xmlFile.WriteStartElement("Code");
                                    xmlFile.WriteString(subitem.ItemCode);
                                    xmlFile.WriteEndElement();
                                }
                                xmlFile.WriteStartElement("Style");
                                xmlFile.WriteString(Enum.GetName(typeof(ItemsStyles), subitem.ItemStyle));
                                xmlFile.WriteEndElement();

                                if (subitem.ItemStyle != ItemsStyles.image)
                                {
                                    xmlFile.WriteStartElement("Text");
                                    xmlFile.WriteString(subitem.Text);
                                    xmlFile.WriteEndElement();
                                }

                                //if (subitem.ItemStyle != ItemsStyles.text)
                                //{
                                    xmlFile.WriteStartElement("Image");
                                    xmlFile.WriteString(subitem.ItemImage);
                                    xmlFile.WriteEndElement();
                                //}
                            }

                            xmlFile.WriteEndElement();//Close Subitem
                        }
                    }
                }

                xmlFile.WriteEndElement();//Close Item
            }
            xmlFile.WriteEndElement(); // Close Toolbar
            xmlFile.Flush();
            xmlFile.Close();
        }

        private void menu_code_Click(object sender, EventArgs e)
        {
            //if (FileName == null)
            //{
            //    MessageBox.Show("You have to save the toolbar first");
            //}else{
            SaveToolbar(TempFilename);
            main.system_open(TempFilename);
            main.Focus();
            //}
        }
        private void refresh_Click(object sender, EventArgs e)
        {
            SaveToolbar(TempFilename);
            Notepad_X.Classes.Toolbar nPreview = new Notepad_X.Classes.Toolbar();
            nPreview.Create(TempFilename);
            nPreview.nToolbar.Name = "previewToolbar";
            if (previewGroup.Controls.ContainsKey("previewToolbar"))
            {
                previewGroup.Controls.RemoveByKey("previewToolbar");
            }
            previewGroup.Controls.Add(nPreview.nToolbar);

        }

        private void Editor_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (System.IO.File.Exists(TempFilename))
            {
                System.IO.File.Delete(TempFilename);
            }
        }

       


        }
}
